package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"yk/common"
	"yk/models"
)

type UserController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Zc() {
	name := c.GetString("name")
	password := c.GetString("password")
	user := models.User{
		Name:     name,
		Password: common.Md5Password(password),
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "注册成功",
			Data: user,
		}
		c.ServeJSON()

	}
}
func (c *UserController) Login() {
	name := c.GetString("name")
	password := c.GetString("password")
	var user models.User
	err := models.DB.Where("name=?", name).First(&user).Error
	key := "lock-" + name
	count, _ := models.Rdb.Get(key).Int()
	if count > 3 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "账号已封禁 两小时后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 1001,
			Msg:  "用户名不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		if user.Password == common.Md5Password(password) {
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "登录成功",
				Data: user,
			}
			c.ServeJSON()
		} else {
			models.Rdb.Incr(key)
			models.Rdb.Expire(key, time.Hour*2)
			c.Data["json"] = JsonR{
				Code: 1002,
				Msg:  "密码错误",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
	}

}
